<template>
  <div>
    <!--数据列表-->
    <div class="table-container">
      <el-radio-group v-model="listQuery.tab" style="margin-bottom:20px;" size="small" @change="handleSearchList">
        <el-radio-button label="myRetain">我的</el-radio-button>
        <el-radio-button label="allRetain">全部</el-radio-button>
      </el-radio-group>
      <vxe-grid ref='retainXGrid' v-bind="gridOptions"  size="mini" :loading="listLoading">
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count">
              </el-pagination>
            </div>
          </div>
        </template>
        <template #toolbar_buttons>
          <el-button type="primary" size="small" @click="addBL">新增保留</el-button>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <div @click="toDetail(row)" type="primary"  style="font-size:12px;vertical-align: middle;cursor:pointer;text-align: center;color:#409EFF">
            <div>{{row.customerName}}</div>
            <div>{{row.kingNumber}}</div>
          </div>
        </template>
        <template #num2_default="{ row, rowIndex }">
          <span v-for="item in row.relationCustomers" style="padding-left:10px">{{item.customerName}}</span>
        </template>
      </vxe-grid>
    </div>

    <el-dialog :close-on-click-modal="false" title="新增保留" :visible.sync="dialogVisible" width="400px">
       <div style="text-align: center;padding:20px 0">设置客户产品线保留后，超6个月未成交不会进入共享池</div>
       <el-form :model="form" size="mini" label-width="100px"  ref="form" :rules="rules">
           <el-form-item label="客户名称：" prop="customerId">
             <el-select
               clearable
               @change="changeCustomerId"
               v-model="form.customerId"
               filterable
               remote
               reserve-keyword
               placeholder="请输入关键词"
               :remote-method="querySearch">
               <el-option
                 v-for="item in querySearchList"
                 :key="item.customerId"
                 :label="item.customerName"
                 :value="item.customerId">
               </el-option>
             </el-select>
           </el-form-item>
           <el-form-item label="产品线：" prop="cglIds">
             <el-select v-model="form.cglIds"  clearable>
               <el-option :label="item.goodsName" v-for="item in goodsLineList" :value="item.cglId" :key="item.cglId"></el-option>
             </el-select>
         </el-form-item>

         <el-form-item label="保留原因：" prop="cglRetainRemark">
           <el-input v-model="form.cglRetainRemark"  :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
         </el-form-item>

       </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getOrderUsersList,getCustomerOption,} from '@/api/partner'
import {planGoodsListScheduled,} from '@/api/order'
import {goodsLineMyGoodsLine,retainGoodLine,getGoodsLine} from '@/api/company'
import {formatDate} from '@/utils/date';

import store from '@/store'
import { mapGetters } from 'vuex'

const defaultListQuery={
  tab:'myRetain',
  chargeId:'',
  "isMainCustomer" : "", //(筛选主客户，1是)
  "customerId" : '', //客户筛选
  "goodsLineId" : '', //客户产品线筛选
  "cglMyChargeTime" : [], //负责日期
  "cglCreateTime" : [], //创建时间
  "cglCustomerLabel" : "", //客户标签,多个逗号隔开
  "cglTrackingTimeType" : "", //跟进时间时间类型(今天-today,7天内-sevenDays,超7天-sevenDaysMore,超15天-fifteenDaysMore，超30天-thirtyDaysMore)
  "cglOrderTimeType" : "", //最新成交时间类型(超7天-sevenDaysMore，超15天-fifteenDaysMore，超30天-thirtyDays,超60天-thirtyDaysMore，超90天-ninetyDaysMore)
  "orderBy" : "", //排序(排序(最近跟进时间-trackingTimeDesc,最近成交时间-cglOrderTime,最新跟进成交时间-trackingOrderTime,更进时间倒序-trackingTimeDesc))
  "pageNum" : 1,
  "pageSize" : 10
};

const defaultForm = {
  "cglIds": "" ,   //产品线id,
  "isRetain": 1 ,   //1-是，0-否,
  "cglRetainRemark": "" ,   //保留原因,
}

export default {
  name: "index",
  data(){
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      count: 0,
      listLoading: false,
      roles:store.getters.roles ? store.getters.roles : [],
      userOptionList:[],

      gridOptions:{
        loading:this.listLoading,
        border: true,
        id: 'retainPl',
        align:'center',
        autoResize:true,
        size:'mini',
        rowConfig: {
          keyField: 'cglId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        checkboxConfig:{
          reserve:true
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        spanMethod({ row, rowIndex, $rowIndex, _rowIndex, column, columnIndex, $columnIndex, _columnIndex, visibleData }){
          let fields = ['orderSn','createTime','customerName','userRealName','timeSureDate','financeTime']
          if(!fields.includes(column['field'])){
            return { rowspan: 1, colspan: 1 }
          }else if(row['isMerge'] && (fields.includes(column['field']))){
            return { rowspan: row['rowNum'], colspan: 1 }
          }else {
            return { rowspan: 0, colspan: 0 }
          }

        },
        columns: [
          {
            field: 'customerName',
            title: '客户名称',
            width: 150,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'goodsLineName',
            title: '产品线',
            width: 100,
          },
          {
            field: 'relationCustomers',
            title: '子客户',
            width: 150,
            slots: {
              // 使用插槽模板渲染
              default: 'num2_default',
            }
          },
          {
            field: 'cglTrackingTime',
            title: '最近跟进时间',
            width: 150,

          },
          {
            field: 'cglTrackingContent',
            title: '最近跟进内容',
            showOverflow:true,
            width: 150,

          },
          {
            field: 'cglOrderNum',
            title: '成交量',
            width: 100,
          },
          {
            field: 'cglOrderTime',
            title: '最近成交时间',
            width: 150,
          },
          {
            field: 'cglUserName',
            title: '负责人',
            width: 100,
          },
          {
            field: 'chargeDayNum',
            title: '持有天数',
            width: 100,
          },
          {
            field: 'shareUserNames',
            title: '共享人',
            width: 100,
          },
          {
            field: 'cglMyChargeTime',
            title: '负责日期',
            width: 150,
          },
          {
            field: 'cglRetainRemark',
            title: '保留原因',
            width: 150,
            showOverflow:true,
          },
          {
            field: '',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用 JSX 渲染
              default: ({ row }) => {
                return [
                  <el-button style="margin-right:10px;" type="text" size="small" onClick={ () => this.cancelql(row.cglId) }>取消保留</el-button>,
                ]
              }
            },
          },
        ],
        data:[],
      },

      list:[],

      dialogVisible:false,
      form: JSON.parse(JSON.stringify(defaultForm)),
      querySearchList:[],
      rules:{
        customerId:[{required: true, message: '此项必填', trigger: 'change'},],
        cglIds: [{required: true, message: '此项必填', trigger: 'change'},],
        cglRetainRemark:[{required: true, message: '此项必填', trigger: 'blur'},],
      },
      btnLoading:false,
      goodsLineList:[]
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    departmentPL(){
      if(this.roles.indexOf("departmentPL") != -1){
        return true
      }else{
        return false
      }
    },
  },
  components : {

  },
  created() {

  },
  filters: {

  },
  methods:{
    changeCustomerId(){
      this.goodsLineList = [];
      this.form.goodsLineId= '';
      getGoodsLine({customerId:this.form.customerId}).then((res)=>{
        this.goodsLineList = res
      })
    },
    toDetail(item){
      let routeData = this.$router.resolve({name:'customerGoodsLineInfo',query:{id:item.customerId}});
      window.open(routeData.href);
    },


    //新增保留
    addBL(){
        this.dialogVisible = true;
        this.form = JSON.parse(JSON.stringify(defaultForm))
    },
    handleClose(){
      this.dialogVisible = false
    },
    handleConfirm(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let pa = JSON.parse(JSON.stringify(this.form));
          retainGoodLine(pa).then(()=>{
            this.btnLoading = false;
            this.dialogVisible = false;
            this.getList()
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },
    //批量取消
    margeQX(){
      let list = this.$refs.retainXGrid.getCheckboxReserveRecords();
      let list2 = this.$refs.retainXGrid.getCheckboxRecords();
      let records = JSON.parse(JSON.stringify(list.concat(list2)));
      if(records.length == 0){
        this.$message({
          type: 'info',
          message: '请先选择记录！'
        });
        return false
      }
      let cglIds = []
      records.forEach((el)=>{
        cglIds.push(el.cglId)
      })
      this.cancelql(cglIds.join(","))
    },

    cancelql(cglIds){
      this.$confirm('取消后超过6个月未成交进入共享池，确认取消此保留？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        retainGoodLine({cglIds:cglIds,isRetain:0}).then(()=>{
          this.getList()
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },

    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= '') {
        getCustomerOption({keywords: queryString}).then((res) => {
          this.querySearchList = res;
        })
      }
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
    },

    //选择员工名称
    handleSelectUserName(key,item){
      this.listQuery[key] = item.userId;
    },

    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let listQuery = JSON.parse(JSON.stringify(this.listQuery))
      goodsLineMyGoodsLine(listQuery).then(response => {
        this.gridOptions.data = []
        response.list.forEach((el,i)=>{
          let newEL = JSON.parse(JSON.stringify(el));
          delete newEL.goodsLineList
          el.goodsLineList.forEach((ee,ii)=>{
            let newEE = JSON.parse(JSON.stringify(ee));
            if(ii == 0){
              console.log("ii",ii)
              newEE.isMerge = true;
              newEE.rowNum = el.goodsLineList.length;
            }else{
              newEE.isMerge = false;
              newEE.rowNum = 0;
            }
            let copy = Object.assign({},newEL,newEE);
            this.gridOptions.data.push(copy);
          })
        })
        this.count = response.count;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },

  },
}
</script>

<style  lang="scss">

.mergeCell .vxe-cell{padding:0;}
.mergeDiv{
  padding-left:10px;
  padding-right:10px;
  border-bottom:1px solid #e8eaec;
  min-height: 36px;
}

.mergeDiv:last-child{
  border-bottom: 0;
}
</style>
